/*
 * Copyright 2008 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.db4o.groovy;

import com.db4o.ObjectContainer;
import groovy.lang.GroovyShell;
import groovy.lang.Script;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author klevgert
 */
public class Db4oGroovyShell extends GroovyShell implements Db4oScriptShell {

  protected String script = "";
  protected ObjectContainer objectContainer;

  public Db4oGroovyShell() {
  }

  public Db4oGroovyShell(ObjectContainer objectContainer) {
    this.setObjectContainer(objectContainer);
  }

  public Object run() {
    if( this.script == null ) {
      Logger.getLogger(Db4oGroovyShell.class.getName()).log(Level.SEVERE,
              "script must be set to call this method");
    }
    return this.run(this.script);
  }

  public Object run(String script) {
    try {

      final Script scriptObj = this.parse(script);
      Object result = scriptObj.run();
      return result;

    } catch (Exception ex) {
      Logger.getLogger(Db4oGroovyShell.class.getName()).log(Level.SEVERE, null, ex);
    }
    return null;
  }

  public ObjectContainer getObjectContainer() {
    return objectContainer;
  }

  public void setObjectContainer(ObjectContainer objectContainer) {
    this.objectContainer = objectContainer;
    this.setVariable("objectContainer", this.objectContainer);
  }

  public String getScript() {
    return script;
  }

  public void setScript(String script) {
    this.script = script;
  }
}
